# -*- coding:utf-8 -*-
import MySQLdb, json
import os
os.sys.path.append('../../utils/constants/')
from constants import *

class jiongDao(object):
    "jiong: let me tell u sth about storage-visiting"
    def __init__(self, mysql_conn):
        self.__copy_list = [ (type(''), "content"), \
                             (type(10), "jiong_uid"), \
                             (type(u''), "jiong_uname"), \
                             (type(''), "uip"), \
                             (type(10), "creat_time"),]
        self.__db_jiong_table = 'jiong'
        self.__list_size = 20
        self.__jiong_output_list = ['jiong_id', 'jiong_uid', 'jiong_uname', 'uip', 'creat_time', 'comm_count',\
                'like_count', 'hate_count', 'content', ]
        self.__db_conn     = mysql_conn

    def __is_valid(self, jiong_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        if not jiong_item:
            ret['retcode'] = E_VALUE_NONE
            ret['message'] = 'jiong_item is None'
            return ret
        for key_item in self.__copy_list:
            if not jiong_item.has_key(key_item[1]):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = 'field[%s] not exist' % (key_item[1], )
                return ret
            if type(jiong_item[key_item[1]]) != key_item[0]:
                ret['retcode'] = E_VALUE_TYPE_ERROR
                ret['message'] = 'field[%s] type error. wish[%s]' % (key_item[1], key_item[0],)
                return ret
            if None == jiong_item[key_item[1]]:
                ret['retcode'] = E_VALUE_IS_EMPTY
                ret['message'] = 'field[%s] empty value' % (key_item[1], )
                return ret
        return ret

    def remove(self, delete_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"

        key_list = ['jiong_id', 'status',]
        for key in key_list:
            if not delete_item.has_key(key):
                ret['retcode'] = E_KEY_NOT_EXIST
                ret['message'] = "delete_item field [%s] not exist" % (key, )
                return ret
        strSQL = 'UPDATE %s SET status = %u WHERE jiong_id = %u;' % \
                (self.__db_jiong_table, delete_item['status'], delete_item['jiong_id'], )
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret
    def add(self, jiong_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        check_ret = self.__is_valid(jiong_item)
        if 0 != check_ret['retcode']:
            return check_ret
        jiong4insert = {}
        for key in self.__copy_list:
            jiong4insert[key[1]] = jiong_item[key[1]]
        # 把tags变成一个字符串
        #if jiong_item.has_key('tags') and type(jiong_item['tags']) == type([]):
        #    jiong4insert['tags'] = '_'.join(jiong_item['tags'])
        #else:
        #    jiong4insert['tags'] = ''
        field_list = 'jiong_uid, jiong_uname, uip, content, creat_time'
        conn = self.__db_conn._db
        value = '%u, "%s", "%s", "%s", %u' % (\
                jiong4insert['jiong_uid'],\
                conn.escape_string(jiong4insert['jiong_uname']),\
                conn.escape_string(jiong4insert['uip']),\
                conn.escape_string(jiong4insert['content'].replace('%', '％')),\
                #conn.escape_string(jiong4insert['tags']),\
                jiong4insert['creat_time'],)
        strSQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self.__db_jiong_table, field_list, value,)
        # -1- 插入jiong表
        #print strSQL
        self.__db_conn.execute(strSQL)
        return ret

    def like(self, like_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # 检查合法性
        if not like_item.has_key('jiong_id') or not like_item.has_key('like'):
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "like_item field [%s] or [%s] not exist" % ('jiong_id', 'like', )
            return ret
        # -1- 更新jiong的like计数，锁表控制并发??
        #self.__db_conn.autocommit(False)
        strSQL  = 'SET AUTOCOMMIT = 0;'
        strSQL += ' SELECT like_count FROM jiong WHERE jiong_id=%u FOR UPDATE;' % (like_item['jiong_id'],)
        strSQL += ' UPDATE jiong SET like_count = like_count+1, hot_count = hot_count+1 WHERE jiong_id=%u;' %\
                (like_item['jiong_id'],)
        strSQL += ' COMMIT; SET AUTOCOMMIT = 1;'
        #print strSQL
        self.__db_conn.execute(strSQL)
        #self.__db_conn.commit()
        #self.__db_conn.autocommit(True)
        return ret

    def hate(self, hate_item):
        ret = {}
        ret['retcode'] = 0
        ret['message'] = "OK"
        # 检查合法性
        if not hate_item.has_key('jiong_id') or not hate_item.has_key('hate'):
            ret['retcode'] = E_KEY_NOT_EXIST
            ret['message'] = "hate_item field [%s] or [%s] not exist" % ('jiong_id', 'hate', )
            return ret
        # -1- 更新jiong的hate计数，锁表控制并发??
        strSQL  = 'SET AUTOCOMMIT=0;'
        strSQL += ' SELECT hate_count FROM jiong WHERE jiong_id=%u FOR UPDATE;' % (hate_item['jiong_id'],)
        strSQL += ' UPDATE jiong SET hate_count = hate_count+1, hot_count = hot_count-1 WHERE jiong_id=%u;' %\
                (hate_item['jiong_id'],)
        strSQL += ' COMMIT; SET AUTOCOMMIT=1;'
        self.__db_conn.execute(strSQL)
        #print strSQL
        return ret

    def query_by_uid(self, uid, pageno):
        select_list = self.__jiong_output_list
        select_key_string = ', '.join(select_list)
        strSQL = 'SELECT %s FROM %s WHERE jiong_uid = %u and status = 0  ORDER BY jiong_id DESC limit %u, %u;' %\
                (select_key_string, self.__db_jiong_table, uid, pageno*self.__list_size, self.__list_size)
        output_list = self.__db_conn.query(strSQL)
        if output_list:
            return output_list
        else:
            return []
    def query_by_time(self, trunc_time, pageno):
        select_list = self.__jiong_output_list
        select_key_string = ', '.join(select_list)
        strSQL = ''
        if trunc_time:
            strSQL = 'SELECT %s FROM %s WHERE creat_time > %u and status = 0 ORDER BY hot_count DESC limit %u, %u;' %\
                    (select_key_string, self.__db_jiong_table, trunc_time, pageno*self.__list_size, self.__list_size)
        else:
            strSQL = 'SELECT %s FROM %s WHERE status = 0 ORDER BY hot_count DESC limit %u, %u;' %\
                    (select_key_string, self.__db_jiong_table, pageno*self.__list_size, self.__list_size)
        output_list = self.__db_conn.query(strSQL)
        if output_list:
            return output_list
        else:
            return []
